const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const routerLoader = require('require-directory')
const koaBody = require('koa-body').koaBody
const cors=require('koa-cors')

// 路由访问中会获取到
const db = require('./db/mysql')
app.use(async (ctx, next) => {
  ctx.db = db;
  await next();
})

// error handler
onerror(app)

// middlewares
// app.use(bodyparser())
//app.use(bodyparser())
app.use(json())
app.use(logger())
app.use(koaBody({
  multipart: true
}));
app.use(require('koa-static')(__dirname + '/public'))
routerLoader(module, './routes', { visit: r => app.use(r.routes()) })

// routes
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app